<?php

namespace Wechat\Controller;

class GroupController extends CommonController {

    public function index() {
        $this->assign("statusEnum", C("ORDER_STATUS"));
        $this->display("index");
    }

    public function endOrder() {
        $this->assign("statusEnum", C("ORDER_STATUS"));
        $this->display("endOrder");
    }

    public function orderList() {

        $status = I("post.status");
        $pageNum = I("post.pageNum") ? I("post.pageNum") : 1;

        $map["o.customer_id"] = $this->customer["customer_id"];

        if($status == "waiting") {
            $map["o.status"] = array("in", array(
                C("ORDER_STATUS.WAITING_OPEN"),
                C("ORDER_STATUS.WAITING_CHOOSE")
            ));
        } else if($status == "end") {
            $map["o.status"] = array("in", array(
                C("ORDER_STATUS.WIN"),
                C("ORDER_STATUS.FAILURE")
            ));
        } else {
            echo json_encode(null);
            exit();
        }

        $list = D("Order")->alias("o")
            ->join("left join __ROUND__ r on r.round_id = o.round_id")
            ->join("left join __PRODUCT__ p on p.product_id = r.product_id")
            ->join("left join __GROUP__ g on g.group_id = o.group_id")
            ->join("left join __CUSTOMER__ c on c.customer_id = g.customer_id")
            ->where($map)
            ->field("c.nickname as group_name, r.progress, r.winner_customer_id, o.customer_id,r.pie_type,
             p.end_time,o.order_id,o.status, o.number, o.create_time, p.price, p.product_name, p.image, g.reward")
            ->order("o.order_id desc")
            ->limit(($pageNum-1)*C("DEFAULT_PAGE_SIZE"), C("DEFAULT_PAGE_SIZE"))
            ->select();

        echo json_encode($list);

    }

    public function preparePayForJoin() {

        $data["code"] = 200;

        $groupId = I("post.groupId");
        $number = I("post.number");

        $group = D("Group")->queryById($groupId);
        if(isNullOrEmpty($group)) {
            $data["code"] = -1;
            $data["msg"] = "对不起，您要加入的团不存在";
            echo json_encode($data);
            exit();
        }

        if($group["status"]
            == C("GROUP_STATUS.WAITING_PAY")) {
            $data["code"] = -2;
            $data["msg"] = "对不起，您要加入的团暂时不可加入";
            echo json_encode($data);
            exit();
        }

        $round = D("Round")->queryById($group["round_id"]);

        if(isNullOrEmpty($round)) {
            $data["code"] = -3;
            $data["msg"] = "对不起，商品未开放，请及时关注";
            echo json_encode($data);
            exit();
        }

        $product = D("Product")->queryById($round["product_id"]);

        $leftNumber = $product["price"] - $round["join_number"];

        if($number > $leftNumber) {
            $data["code"] = -4;
            $data["msg"] = "对不起，剩余份数不足，请重新选择";
            echo json_encode($data);
            exit();
        }

        $payId = D("Pay")->add(array(
            'out_trade_no' => time() . rand(0, 999),
            'money' => $number,
            'status' => 0,
            'callback' => "",
            'create_time' => getCurrentDate(),
            'update_time' => getCurrentDate()
        ));

        $orderData["round_id"] = $round["round_id"];
        $orderData["customer_id"] = $this->customer["customer_id"];
        $orderData["create_time"] = getCurrentDate();
        $orderData["number"] = $number;
        $orderData["group_id"] = $groupId;
        $orderData["status"] = C("ORDER_STATUS.WAITING_PAY");
        $orderData["pay_id"] = $payId;

        $orderId = D("Order")->add($orderData);

        $data["order_id"] = $orderId;

        echo json_encode($data);

    }

    public function preparePay() {

        $data["code"] = 200;

        $roundId = I("post.roundId");
        $number = I("post.number");
        $note = I("post.note");

        if(isNullOrEmpty($note)) {
            $data["code"] = -1;
            $data["msg"] = "对不起，团长令不能为空";
            echo json_encode($data);
            exit();
        }

        $round = D("Round")->queryById($roundId);

        if(isNullOrEmpty($round)) {
            $data["code"] = -2;
            $data["msg"] = "对不起，商品未开放，请及时关注";
            echo json_encode($data);
            exit();
        }

        $product = D("Product")->queryById($round["product_id"]);

        $leftNumber = $product["price"] - $round["join_number"];

        if($number > $leftNumber) {
            $data["code"] = -3;
            $data["msg"] = "对不起，剩余份数不足，请重新选择";
            echo json_encode($data);
            exit();
        }

        $groupMemberMap["g.round_id"] = $round["round_id"];
        $groupMemberMap["gm.customer_id"] = $this->customer["customer_id"];
        $groupMemberMap["g.status"] = array("eq", C("GROUP_STATUS.WAITING_JOIN"));
        $groupMember = D("GroupMember")->alias("gm")
            ->join("left join __GROUP__ g on g.group_id = gm.group_id")
            ->where($groupMemberMap)
            ->field("g.group_id")
            ->find();

        if(!isNullOrEmpty($groupMember)) {
            $data["code"] = -4;
            $data["msg"] = "对不起，此轮已经成为了任一团的团员，不可开团";
            echo json_encode($data);
            exit();
        }

        $groupData["round_id"] = $round["round_id"];
        $groupData["create_time"] = getCurrentDate();
        $groupData["customer_id"] = $this->customer["customer_id"];
        $groupData["status"] = C("GROUP_STATUS.WAITING_PAY");
        $groupData["reward"] = 0;
        $groupData["note"] = $note;

        $groupId = D("Group")->add($groupData);

        $groupMemberData["group_id"] = $groupId;
        $groupMemberData["customer_id"] = $this->customer["customer_id"];
        $groupMemberData["create_time"] = getCurrentDate();
        $groupMemberData["number"] = $number;

        D("GroupMember")->add($groupMemberData);

        $payId = D("Pay")->add(array(
            'out_trade_no' => time() . rand(0, 999),
            'money' => $number,
            'status' => 0,
            'callback' => "",
            'create_time' => getCurrentDate(),
            'update_time' => getCurrentDate()
        ));

        $orderData["round_id"] = $round["round_id"];
        $orderData["customer_id"] = $this->customer["customer_id"];
        $orderData["create_time"] = getCurrentDate();
        $orderData["number"] = $number;
        $orderData["group_id"] = $groupId;
        $orderData["status"] = C("ORDER_STATUS.WAITING_PAY");
        $orderData["pay_id"] = $payId;

        $orderId = D("Order")->add($orderData);

        $data["order_id"] = $orderId;

        echo json_encode($data);

    }

    //等待支付页
    public function payIndex() {

        //支付相关
        $arr = array(
            'appid' => C('appid'),
            'mch_id' => C('mch_id'),
            'nonce_str' => $this->createNoncestr(),
            //'sign' => '',	//签名
            'body' => '真心代喝订单',
            'out_trade_no' => $pay['out_trade_no'], //订单号
            'total_fee' => $order['total_amount'] * 100, //金额
            'spbill_create_ip' => get_client_ip(),
            'notify_url' => C('rooturl') . '/backend/index.php/wechat/api/wechatpay/', //通知地址
            'trade_type' => 'JSAPI',
            'openid' => $this->currentUser['openid'],
        );
        $arr['sign'] = $this->getSign($arr);  //签名

        $post = curl('https://api.mch.weixin.qq.com/pay/unifiedorder', $this->arrayToXml($arr));

        $arr2 = $this->xmlToArray($post);

        $jsApiObj["appId"] = C('appid');
        $timeStamp = time();
        $jsApiObj["timeStamp"] = "$timeStamp";
        $jsApiObj["nonceStr"] = $this->createNoncestr();
        $jsApiObj["package"] = "prepay_id=" . $arr2['prepay_id'];
        $jsApiObj["signType"] = "MD5";
        $jsApiObj["paySign"] = $this->getSign($jsApiObj);
        $parameters = json_encode($jsApiObj);

        $this->returnData['data']['config'] = $this->signature();
        $this->returnData['data']['webarr'] = $jsApiObj;

        $this->response($this->returnData, 'json');

    }
    /**
     * 	作用：生成签名
     */
    public function getSign($Obj) {

        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        $String = $String . "&key=" . C('mch_key');
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = md5($String);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        //echo "【result】 ".$result_."</br>";
        return $result_;
    }

    /**
     * 	作用：array转xml
     */
    function arrayToXml($arr) {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml.="<" . $key . ">" . $val . "</" . $key . ">";
            } else
                $xml.="<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
        $xml.="</xml>";
        return $xml;
    }

    function signature() {
        $Obj['jsapi_ticket'] = jsapi_ticket();
        $Obj['noncestr'] = createNoncestr();
        $Obj['url'] = "http://" . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
        $Obj['timestamp'] = time();

        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        //dump($Parameters);
        $String = formatBizQueryParaMap($Parameters, false);
        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        //$String = $String."&key=".C('mch_key');
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = sha1($String);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        //$Obj['signature'] = strtoupper($String);
        $Obj['signature'] = $String;

        return $Obj;
    }

    /**
     * 	作用：产生随机字符串，不长于32位
     */
    public function createNoncestr($length = 32) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str.= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 	作用：格式化参数，签名过程需要使用
     */
    function formatBizQueryParaMap($paraMap, $urlencode) {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

    /**
     * 	作用：将xml转为array
     */
    public function xmlToArray($xml) {
        //将XML转为array
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }

}